package com.cheetah.handler;

import com.cheetah.annotation.Handler;
import com.cheetah.constants.AttributeKeyConstants;
import com.cheetah.dispatcher.Dispatcher;
import com.cheetah.dispatcher.factory.DispatcherFactory;
import com.cheetah.enums.Protocol;
import com.cheetah.exceptions.CheetahException;
import com.cheetah.exceptions.CheetahRuntimeException;
import com.cheetah.protocol.Request;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@ChannelHandler.Sharable
@Slf4j
@Handler(sharable = true,order = 20)
public class RequestHandler extends SimpleChannelInboundHandler<Request> {

    @Autowired
    private DispatcherFactory dispatcherFactory;

    private Dispatcher getDispatcher(ChannelHandlerContext ctx){
        Object protocol = ctx.channel().attr(AttributeKey.valueOf(AttributeKeyConstants.ATTRIBUTE_KEY_MAGIC)).get();
        Protocol pro = Protocol.getProtocol((short)protocol);
        if(pro ==  null){
            throw new CheetahRuntimeException("not found this protocol!");
        }

        log.info("{} protocol is found",pro.getName());
        return dispatcherFactory.getDispatcher(pro.getName());
    }


    @Override
	protected void channelRead0(ChannelHandlerContext ctx, Request msg) throws Exception{
        getDispatcher(ctx).dispatch(ctx, msg);
	}

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

}
